package xx.iverson.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xx.iverson.exception.BusinessException;
import xx.iverson.result.ReturnResult;

/**
 * xx.iverson.handler.GlobalExceptionHandler
 * 描述：
 * on 2025/7/1-上午10:21
 *
 * @author weijx
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ReturnResult<?> handleBusinessException(BusinessException e) {
        logger.warn("业务异常: {}", e.getMessage());
        // 如果有具体的EnumException，使用它的错误信息
        if (e.getException() != null) {
            return ReturnResult.error(e.getException().getErrorCode(),
                    e.getException().getErrorMsg(),
                    null);
        }
        // 否则使用BusinessException中的信息
        return ReturnResult.error(e.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(Exception.class)
    public ReturnResult<?> handleAllExceptions(Exception e) {
        logger.error("系统异常", e);
        return ReturnResult.error(500, "系统繁忙，请稍后再试", null);
    }
}